﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.Caching;
using System.Web;

namespace blackhouse.BlackApart.Web.Handlers {
    public class UpdateKeepAlive {

        #region Fields

        private string[] urls;

        #endregion

        #region Constructors

        public UpdateKeepAlive() {
            if (!MemoryCache.Default.Contains("UpdateKeepAlive")) {
                this.AddCacheTimer();
                string host = "http://" + HttpContext.Current.Request.Url.Host;
                this.urls = new string[]{
                host + "/Update.aspx",
                host+"/en/Update.aspx"
                };
            }
        }

        private UpdateKeepAlive(string[] urls) {
            if (!MemoryCache.Default.Contains("UpdateKeepAlive")) {
                this.AddCacheTimer();
                this.urls = urls;
            }
        }

        #endregion

        #region Methods

        private void AddCacheTimer() {
            CacheItem ci = new CacheItem("UpdateKeepAlive", this);
            CacheItemPolicy cip = new CacheItemPolicy();
            cip.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(1);
            cip.RemovedCallback = new CacheEntryRemovedCallback(RaiseCacheTimerEnd);
            MemoryCache.Default.Add(ci, cip);
        }

        private void RaiseCacheTimerEnd(CacheEntryRemovedArguments args) {
            UpdateKeepAlive uka = args.CacheItem.Value as UpdateKeepAlive;
            uka.RaiseUpdate();
            new UpdateKeepAlive(uka.urls);
        }

        private void RaiseUpdate() {
            for (int xu = 0; xu < this.urls.Length; xu++) {
                WebRequest request = WebRequest.Create(urls[xu].ToString());
                request.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult ar) { }), null);
                Trace.WriteLine("UPDATE APARTS");
            }
        }

        #endregion

    }
}